package com.flycms.modules.user.annotation.support;

import com.flycms.common.constant.Constants;
import com.flycms.modules.user.annotation.LoginUser;
import com.flycms.modules.user.util.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
	@Autowired
	private JwtTokenUtils jwtTokenUtils;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(Integer.class)
				&& parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

		String token = request.getHeader(Constants.JWT_AUTHORITIES);
		if (token == null || token.isEmpty()) {
			return null;
		}
		return jwtTokenUtils.getUserToken(token);
	}
}
